<?php

namespace App\Console\Commands;

use Carbon\Carbon;
use Illuminate\Console\Command;
use Illuminate\Support\Facades\Http;
use Illuminate\Support\Facades\Log;
use Illuminate\Support\Facades\File;

class FetchTransactionDataCommand extends Command
{
    /**
     * 命令名称
     *
     * @var string
     */
    protected $signature = 'money:fetch-transaction-data {--start=2022-08} {--end=2025-06} {--output=transaction_data.txt}';

    /**
     * 命令描述
     *
     * @var string
     */
    protected $description = '从API获取记账数据并整理到txt文件中';

    /**
     * API URL
     *
     * @var string
     */
    protected $apiUrl = 'https://wxapp.shayujizhang.com/get/list/';

    /**
     * 请求头信息
     *
     * @var array
     */
    protected $headers = [
        'xweb_xhr' => '1',
        'User-Agent' => 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/126.0.0.0 Safari/537.36 MicroMessenger/7.0.20.1781(0x6700143B) NetType/WIFI MiniProgramEnv/Windows WindowsWechat/WMPF WindowsWechat(0x63090c33)XWEB/13839',
        'Content-Type' => 'application/json',
        'Accept' => '*/*',
        'Sec-Fetch-Site' => 'cross-site',
        'Sec-Fetch-Mode' => 'cors',
        'Sec-Fetch-Dest' => 'empty',
        'Referer' => 'https://servicewechat.com/wx6d5af84d354f6717/24/page-frame.html',
        'Accept-Encoding' => 'gzip, deflate, br',
        'Accept-Language' => 'zh-CN,zh;q=0.9'
    ];

    /**
     * 会话令牌
     *
     * @var string
     */
    protected $thirdSession = 'eyJhbGciOiJIUzI1NiIsImV4cCI6MTc0OTY1NjkzNywiaWF0IjoxNzQ5NjUzMzM3fQ.eyJ0ZW1wX2tleSI6Ind3dy5zaGF5dWppemhhbmcuY29tL3d4YXBwL0NKZUN1d3BFVVBKY0JkS2ZCalgyaFAifQ.Enhd_pF7OVk6hG-LddtJ5ruEn-fKpmWGEFjuqSqOw0E';

    /**
     * 执行命令
     */
    public function handle()
    {
        $startDate = Carbon::parse($this->option('start') . '-01');
        $endDate = Carbon::parse($this->option('end') . '-01')->endOfMonth();
        $outputFile = $this->option('output');
        
        $this->info('开始获取记账数据...');
        $this->info('时间范围: ' . $startDate->format('Y-m-d') . ' 至 ' . $endDate->format('Y-m-d'));
        $this->info('输出文件: ' . $outputFile);
        
        // 创建或清空输出文件
        File::put(storage_path($outputFile), '');
        
        $currentDate = clone $startDate;
        $totalRecords = 0;
        
        $this->output->progressStart($endDate->diffInMonths($startDate) + 1);
        
        while ($currentDate->lte($endDate)) {
            $year = $currentDate->format('Y');
            $month = $currentDate->format('m');
            
            try {
                $records = $this->fetchMonthData($year, $month);
                $this->processRecords($records, $outputFile);
                $totalRecords += count($records);
                $this->output->progressAdvance();
            } catch (\Exception $e) {
                $this->error("获取 {$year}-{$month} 数据失败: {$e->getMessage()}");
                Log::error("获取记账数据异常", [
                    'year' => $year,
                    'month' => $month,
                    'error' => $e->getMessage(),
                    'trace' => $e->getTraceAsString()
                ]);
            }
            
            $currentDate->addMonth();
        }
        
        $this->output->progressFinish();
        $this->info("数据获取完成，共处理 {$totalRecords} 条记录，已保存到 {$outputFile}");
        
        return 0;
    }
    
    /**
     * 获取指定月份的数据
     *
     * @param string $year
     * @param string $month
     * @return array
     */
    protected function fetchMonthData($year, $month)
    {
        $url = $this->apiUrl . "{$year}/{$month}/?third_session={$this->thirdSession}";
        
        $response = Http::withHeaders($this->headers)
            ->get($url);
            
        if ($response->successful()) {
            $data = $response->json();
            
            if (isset($data['code']) && $data['code'] === 0 && isset($data['data'])) {
                return $data['data'];
            } else {
                throw new \Exception('API返回数据格式错误: ' . json_encode($data));
            }
        } else {
            throw new \Exception('API请求失败: ' . $response->status());
        }
    }
    
    /**
     * 处理记录并写入文件
     *
     * @param array $records
     * @param string $outputFile
     * @return void
     */
    protected function processRecords($records, $outputFile)
    {
        $lines = [];
        
        foreach ($records as $record) {
            if (isset($record['category']['category_name']) && 
                isset($record['detail_amount']) && 
                isset($record['record_date'])) {
                
                $categoryName = $record['category']['category_name'] ?? '';
                $amount = $record['detail_amount'] ?? '';
                $date = $record['record_date'] ?? '';
                $description = $record['record_description'] ?? '';
                
                $lines[] = "{$categoryName}\t{$amount}\t{$date}\t{$description}";
            }
        }
        
        if (!empty($lines)) {
            File::append(storage_path($outputFile), implode("\n", $lines) . "\n");
        }
    }
}